<?php

class Model {

      public $table; //操作的数据表
      protected $opt; //查询参数
      protected $pri; //表主键

      function __construct($table) {
            $this->table = $table;
            $db = @mysql_connect(C("DB_HOST"), C("DB_USER"), C("DB_PSW")); //连接数据库
            if (!$db) {
                  halt("数据库连接失败");
            }
            mysql_select_db(C('DB_NAME')); //选择数据库
            mysql_query("SET NAMES " . C("DB_CHARSET")); //设置字符集
            $this->getPrimary($table);//获取表主键
            $this->opt(); //初始化查询参数（还原查询参数）
      }

      //limit语句
      function limit($arg) {//链式操作$db->limit(2)->select();中 $db->limit(2)要返回一个对象
            $this->opt['limit'] = " limit $arg ";
            return $this;
      }

      //field语句
      function field($arg) {
            $this->opt['field'] = " $arg ";
            return $this;
      }

      //order语句
      function order($arg) {
            $this->opt['order'] = " order by $arg ";
            return $this;
      }

      //where语句
      function where($arg) {
            $this->opt['where'] = " where $arg ";
            return $this;
      }

      //group语句
      function group($arg) {
            $this->opt['group'] = " group by $arg ";
            return $this;
      }

      //having语句
      function having($arg) {
            $this->opt['having'] = " having $arg ";
            return $this;
      }

      /**
       * 定义基本查询参数
       */
      protected function opt() {
            $this->opt = array(
                "table" => $this->table,
                "pri"=>  $this->pri,              
                "where" => '',
                "group" => '',
                "having" => '',
                "order" => '',
                "limit" => '',
                "field" => ' * '
            );
      }

      //临时更换表
      function table($table) {
            $this->opt['table'] = $table;
            return $this;
      }
      private function getPrimary($table){
            $sql="desc ".$table;
            $field=$this->query($sql);
            foreach ($field as $f){
                  if($f["Key"]=="PRI"){
                        $this->pri=$f['Field'];//定义表的主键
                        return;
                  }
            }
      }

      /**
       * 发送sql语句
       * @return type
       */
      public function select() {
            $sql = "select" . $this->opt['field'] . 'from ' . $this->opt['table'] . $this->opt['where'] . $this->opt['group'] . $this->opt['having'] . $this->opt['order'] . $this->opt['limit'];
            $this->opt(); //初始化查询参数
            return $this->query($sql);
      }

      //select()函数的别名
      public function all() {
            return $this->select();
      }

      //插入数据
      public function insert($data = null) {
            if ($data == null) {
                  $data = $_POST;
            }
            if (!is_array($data)) {//要拆分字段，所以不是数组返回false
                  return FALSE;
            }
            $field = implode(",", array_keys($data)); //拆分 array_keys()数组中的key键
            $value = "'" . implode("','", array_values($data)) . "'"; //拆分 array_values()数组中的values键
            $sql = "insert into " . $this->opt['table'] . "($field) values($value)";
            return $this->exe($sql); //返回 执行发送$sql
      }

      //发送增删改的$sql
      public function exe($sql) {
            if (mysql_query($sql)) {
                  //返回新增的id或和受影响的条数
                  return mysql_insert_id() ? mysql_insert_id() : mysql_affected_rows();
            }
      }

      //删除数据
      public function del() {
            $where = $this->opt['where'];
            if (!$where) {
                  echo "del方法必须存在where条件";exit;
            }
            $sql = "delete from " . $this->opt['table'] . $where;
            return $this->exe($sql);
      }

      //修改数据
      function update($data = null) {
            if ($data == null) {
                  $data = $_POST;
            }
            if (!is_array($data)) {//要拆分字段，所以不是数组返回false
                  return FALSE;
            }
            $where = $this->opt['where'];
            if(isset($data[$this->opt['pri']])){
                  $where="where ".$this->opt['pri'].'='.$data[$this->opt['pri']];
            }            
            if (!$where) {
                  echo "update方法必须存在where条件";exit;
            }
            $set = '';
            foreach ($data as $k => $v) {
                  $set.=$k . "='" . $v . "',"; //组合成 sid='6',sname='小强',sex='1'  这个样式
            }
            $set = substr($set, 0, -1); //echo $set=sid='6',sname='小强',sex='1',  去掉最后一个  ,   
            $sql = "update " . $this->opt['table'] . " set $set " . $where;
            return $this->exe($sql);
      }

      /**
       * 发送有结果集的sql
       * @param type $sql
       */
      public function query($sql) {
            $result = mysql_query($sql);
            if (!$result) {
                  $this->error(); //执行错误方法
            }
            $rows = array();
            while ($row = mysql_fetch_assoc($result)) {
                  $rows[] = $row; //把得到的结果存入数组
            }
            return $rows;
      }

      private function error() {//发送错误时，执行的方法
            echo mysql_error();
            exit;
      }

}

?>
